<template>
  <el-drawer
    :title="copName"
    size="60%"
    :visible.sync="isShowDrawer"
    @close="closeDrawer"
  >
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        :rules="rules"
        label-width="140px"
        label-suffix="："
      >
        <div class="property-title">政策属性</div>
        <el-form-item label="政策类型" prop="marketingType">
          <el-select v-model="param.marketingType" class="w400" placeholder="选择政策类型" disabled @change="selectMarkingType">
            <el-option
              v-for="item in filters.marketType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="政策名称" prop="marketingName">
          <el-input
            v-model="param.marketingName"
            class="w400"
            placeholder="请输入政策名称"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item v-if="param.marketingType == '1'" label="赠送类型">
          <el-select v-model="param.giveType" placeholder="选择赠送类型" @change="changeType">
            <el-option
              v-for="item in filters.giveTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div class="df_ac">
          <el-form-item label="政策规则" prop="amount">
            <span class="mr10">订单实付满</span>
            <el-input-number v-model="param.amount" :min="0" :step="1" class="w100 mr10" />
            <!-- <el-input
              v-model="param.amount"
              class="w100"
              placeholder=""
              onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/);this.dispatchEvent(new Event('input'))"
            /> -->
            <span class="mr10">元</span>
            <span v-if="param.marketingType == '0'" class="mr10">减</span>
          </el-form-item>
          <template v-if="param.marketingType == '0'">
            <el-form-item label-width="0" prop="discountNum">
              <el-input-number v-model="param.discountNum" :min="0" :step="1" class="w100 mr10" />
              <!-- <el-input
                v-model="param.discountNum"
                class="w200"
                placeholder="请输入满减金额"
                onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/);this.dispatchEvent(new Event('input'))"
              /> -->
              <span class="mr10">元</span>
            </el-form-item>
          </template>
          <template v-else>
            <div v-if="param.giveType == '1'" class="df_ac">
              <el-form-item label-width="0">
                <span class="mr10">赠送物品</span>
                <el-input
                  v-model="param.giveItems"
                  class="w200 mr10"
                  placeholder="请输入物品名称"
                />
              </el-form-item>
              <!-- <el-form-item label-width="0">
                <span class="mr10">赠送数量</span>
                <el-input
                  v-model="param.giveNum"
                  class="w100"
                  placeholder=""
                  onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/);this.dispatchEvent(new Event('input'))"
                />
              </el-form-item> -->
            </div>
            <div v-else>
              <el-form-item label-width="0">
                <span class="mr10">赠送</span>
                <el-input-number v-model="param.giveItems" :min="0" :step="1" class="w100 mr10" />
                <!-- <el-input
                  v-model="param.giveItems"
                  class="w200"
                  placeholder="请输入赠送金额"
                  onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/);this.dispatchEvent(new Event('input'))"
                /> -->
                <span>元</span>
              </el-form-item>
            </div>
          </template>
        </div>
        <el-form-item label="倍数叠加" prop="isDouble">
          <el-radio v-model="param.isDouble" label="1">支持</el-radio>
          <el-radio v-model="param.isDouble" label="0">不支持</el-radio>
          <span class="placeholder9">开启叠加使用，则支持叠加扣减；例如：政策配置满100减50，订单金额为200会减100</span>
        </el-form-item>
        <el-form-item label="优先级">
          <el-input
            v-model="param.rank"
            class="w400"
            placeholder="数字越小优先级越高"
          />
        </el-form-item>
        <div class="property-title">时间设置</div>
        <el-form-item label="使用日期" prop="useTimes">
          <el-date-picker
            v-model="param.useTimes"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="时间段限制" prop="timer">
          <el-radio v-model="param.rulesTimeSectionFlag" label="1" @change="changeTimeFalg">全时段可用</el-radio>
          <el-radio v-model="param.rulesTimeSectionFlag" label="0" @change="changeTimeFalg">指定时段可用</el-radio>
          <div v-if="param.rulesTimeSectionFlag == '0'">
            <el-checkbox-group v-model="selWeekList" class="mb10">
              <el-checkbox v-for="item in weekList" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
            <div class="df">
              <span class="mr10">每日</span>
              <div>
                <el-time-picker
                  v-model="filters.dateTimes"
                  is-range
                  class="w200 mr10"
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="~"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                />
              </div>
              <span>可用</span>
            </div>
          </div>
        </el-form-item>
        <!-- <div class="line-style" /> -->
        <div class="mb20">
          <span class="property-title">适用规则</span>
          <span class="sub-title">适用的场馆、项目、订单、支付方式</span>
        </div>
        <el-form-item label-width="0" prop="orderTypes">
          <div class="df">
            <span class="order_name"><span class="">*</span> 订单类型：</span>
            <el-radio-group v-model="param.orderTypes" class="flex1" @change="reSelectOrderType">
              <el-radio
                v-for="(item, index) in orderTypeList"
                :key="index"
                :label="item.id"
                class="line24"
              >{{ item.name }}</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="会员等级">
          <el-radio v-model="param.rulesCardLevelFlag" label="1" @change="changeLevel">全部等级可用</el-radio>
          <el-radio v-model="param.rulesCardLevelFlag" label="0" @change="changeLevel">指定等级可用</el-radio>
          <el-checkbox-group v-if="param.rulesCardLevelFlag == '0'" v-model="selCardTypeList">
            <el-checkbox
              v-for="(item, index) in cardlevl"
              :key="index"
              :label="item.id"
            >{{ item.cardName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-radio v-model="param.rulesPayMethodFlag" label="1" @change="changePayMethod">全部支付方式可用</el-radio>
          <el-radio v-model="param.rulesPayMethodFlag" label="0" @change="changePayMethod">指定支付方式可用</el-radio>
          <el-checkbox-group v-if="param.rulesPayMethodFlag == '0'" v-model="selPayTypeList">
            <el-checkbox
              v-for="(item, index) in payTypeList"
              :key="index"
              :label="item.value"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div>
          <el-form-item class="margin-t-20" label="适用场馆">
            <el-radio v-model="param.rulesVenueFlag" label="1" @change="changeVenue">全部场馆可用</el-radio>
            <el-radio v-model="param.rulesVenueFlag" label="0" @change="changeVenue">指定场馆可用</el-radio>
            <div v-if="param.rulesVenueFlag == '0'" class="venue-project">
              <div class="venue-list">
                <el-checkbox-group v-model="checkedVenue" @change="checkVenue">
                  <el-checkbox
                    v-for="(item, index) in venueProjectListData"
                    :key="index"
                    :label="item.id"
                  >{{ item.name }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </el-form-item>
        </div>
        <el-form-item v-if="param.rulesVenueFlag === '0'" label="适用项目">
          <el-radio v-model="param.rulesProjectFlag" label="1" @change="changeItems">全部项目可用</el-radio>
          <el-radio v-model="param.rulesProjectFlag" label="0" @change="changeItems">指定项目可用</el-radio>
          <el-table v-if="param.rulesProjectFlag == '0'" :data="venueProjectListDataForTable" border>
            <el-table-column prop="name" label="场馆" width="200px" />
            <el-table-column label="项目">
              <template slot-scope="scope">
                <el-checkbox-group v-model="checkedItems">
                  <el-checkbox
                    v-for="(item, index) in scope.row.projects"
                    :key="index"
                    :label="item.id"
                    @change="checkProject()"
                  >{{ item.projectName }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <div class="separate" />
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="onSubmit()">提交</el-button>
        <el-button @click="closeDrawer">取消</el-button>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import { rules, weekList } from './config'
import {
  venueList,
  venueProjectList,
  allConfigList,
  cardList,
  marketAdd,
  marketDetail,
  marketEdit,
  orderType
} from '@/api'
// import { parseTime } from '@/utils'
import { pickerOptions } from '@/utils/config'
export default {
  name: 'MarketAdd',
  data() {
    return {
      id: '',
      isShowDrawer: false,
      subLoading: false,

      selWeekList: [],
      weekList,

      pickerOptions,
      rules,
      copName: '新增政策',
      filters: {
        marketType: [
          { value: '0', label: '满减' },
          { value: '1', label: '满赠' }
        ],
        giveTypes: [
          { value: '0', label: '金额' },
          { value: '1', label: '商品' }
        ],
        orderTypes: [
        ],
        money: '',
        circulation: ''
      },
      selectItems: [],
      giftCount: '',
      selPayTypeList: [],
      selCardTypeList: [],
      payTypeList: [],
      selOrderTypeList: [
      ],
      selOrderType: '',
      orderTypeList: [
        { value: '01', label: '会员充值' },
        { value: '02', label: '场次预定' },
        { value: '06', label: '商品购买' },
        { value: '03', label: '门票售卖' }
      ],
      cardlevl: [],
      venueProjectListData: [],
      venueProjectListDataForTable: [],
      projectCheckList: [],
      checkedVenue: [],
      checkedItems: [],
      // dateTimes: [],
      param: {
        rulesCardLevelFlag: '1',
        rulesPayMethodFlag: '1',
        rulesVenueFlag: '1',
        rulesProjectFlag: '1',
        rulesTimeSectionFlag: '1',

        marketingType: '0',
        marketingName: null,
        giveType: '1',
        amount: null, // 实付满多少钱
        discountNum: '', // 满减值
        giveNum: '',
        giveItems: '',
        isDouble: '1',
        rank: '',
        useTimes: [], // 使用日期
        orderTypes: '',
        useRules: {
          // 使用规则
          useStadiums: '', // 适用场馆
          useItems: '', // 适用项目
          orderTypes: '', // 订单类型
          payMethods: '', // 支付方式
          useDateStart: '', // 适用开始日期
          useDateEnd: '', // 适用结束日期
          useTimeStart: '', // 适用开始时间
          useTimeEnd: '', // 适用结束时间
          cardLevel: ''	// 会员卡等级
        }
      }
    }
  },
  created() {
    this.getVenueList()
    this.getVenueProjectList()
    this.getCardlevl()
    this.getPayTypeList()
    this.getOrderType()
  },
  methods: {
    submitData() {
      const that = this
      const { filters } = this
      if (this.param.rank === '') {
        this.param.rank = 1
      }
      if (this.param.marketingType !== '0') {
        if (this.param.giveType === '0') {
          this.param.giveNum = ''
        }
      }
      let param = JSON.stringify(this.param)
      param = JSON.parse(param)
      param.useRules.useStadiums = ''
      param.useRules.useItems = ''
      param.useRules.payMethods = ''
      param.useRules.orderTypes = ''

      if (param.useTimes && param.useTimes.length) { // 日期
        param.useRules.useDateStart = param.useTimes[0]
        param.useRules.useDateEnd = param.useTimes[1]
      }
      if (filters.dateTimes && filters.dateTimes.length > 0) { // 时间
        param.useRules.useTimeStart = filters.dateTimes[0]
        param.useRules.useTimeEnd = filters.dateTimes[1]
      }
      if (this.checkedVenue.length) {
        param.useRules.useStadiums = this.checkedVenue.join(',')
      }
      if (this.checkedItems.length) {
        param.useRules.useItems = this.checkedItems.join(',')
      }
      if (this.selPayTypeList.length) {
        param.useRules.payMethods = this.selPayTypeList.join(',')
      }
      if (this.param.orderTypes.length) {
        param.useRules.orderTypes = this.param.orderTypes
      }
      if (this.selCardTypeList.length) {
        param.useRules.cardLevel = this.selCardTypeList.join(',')
      }
      if (this.selWeekList.length > 0) {
        param.useRules.useDays = this.selWeekList.join(',')
      }

      console.log(param)
      // return
      this.subLoading = true
      if (this.id) {
        marketEdit({ param, userId: sessionStorage.getItem('userId') })
          .then((res) => {
            that.subLoading = false
            if (res.errorCode === '000000') {
              this.$message.success('编辑成功')
              // this.$router.replace(`/marketing/marketing?renovate=1`)
              this.$emit('success')
            }
          })
          .catch((er) => {
            that.subLoading = false
            console.log(er)
          })
      } else {
        marketAdd({
          param: param,
          userId: sessionStorage.getItem('userId')
        })
          .then((res) => {
            that.subLoading = false
            if (res.errorCode !== '000000') return
            this.$message.success('新增成功')
            this.$emit('success')
            // this.$router.replace(`/marketing/marketing?renovate=1`)
          })
          .catch((err) => {
            that.subLoading = false
            console.log(err)
          })
      }
    },
    // 获取政策详情
    getMarketDetailInfo(id) {
      marketDetail({
        param: { id },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          if (res.errorCode === '000000') {
            // console.log('-----------1')
            this.param = res.record
            const { useRules } = this.param
            this.param.amount = this.param.amount.toString()
            const times = [this.param.useRules.useDateStart, this.param.useRules.useDateEnd]
            this.$set(this.param, 'useTimes', times)
            if (useRules.useDays) {
              this.selWeekList = useRules.useDays.split(',')
            }
            if (useRules.useTimeStart && useRules.useTimeEnd) {
              const times = [useRules.useTimeStart, useRules.useTimeEnd]
              this.$set(this.filters, 'dateTimes', times)
            }

            if (this.param.discountNum) {
              this.param.discountNum = this.param.discountNum.toString()
            }
            console.log(this.param)
            if (this.param.useRules.payMethods) {
              this.selPayTypeList = this.param.useRules.payMethods.includes(',')
                ? this.param.useRules.payMethods.split(',')
                : [this.param.useRules.payMethods]
            }
            this.param.useRules.payMethods = ''
            if (this.param.useRules.orderTypes) {
              this.$set(this.param, 'orderTypes', this.param.useRules.orderTypes)
              // this.param.orderTypes = this.param.useRules.orderTypes
              console.log('this.param.orderTypes', this.param.orderTypes)
            }
            if (this.param.useRules.cardLevel) {
              this.selCardTypeList = this.param.useRules.cardLevel.includes(',')
                ? this.param.useRules.cardLevel.split(',')
                : [this.param.useRules.cardLevel]
            }
            this.param.useRules.cardLevel = ''
            if (this.param.useRules.useStadiums) {
              this.checkedVenue = this.param.useRules.useStadiums.includes(',')
                ? this.param.useRules.useStadiums.split(',')
                : [this.param.useRules.useStadiums]
            }
            this.param.useRules.useStadiums = ''
            if (this.param.useRules.useItems) {
              this.checkedItems = this.param.useRules.useItems.includes(',')
                ? this.param.useRules.useItems.split(',')
                : [this.param.useRules.useItems]
            }
            this.param.useRules.useItems = ''
            this.resetVenueProject()
            this.getOrderType()
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    closeDrawer() {
      this.isShowDrawer = false
      this.$emit('close')
    },
    selectMarkingType() {
      this.getOrderType()
    },
    changeVenue(val) {
      this.checkedVenue = []
      if (val === '0') {
        this.venueProjectListDataForTable = []
      } else {
        this.venueProjectListDataForTable = this.venueProjectListData
      }
      this.changeItems()
    },
    changeItems() {
      // this.checkVenue()
      this.checkedItems = []
      this.param.useRules.useItems = ''
    },
    changeLevel(val) {
      if (val === '1') {
        this.selCardTypeList = []
      }
    },
    changePayMethod(val) {
      if (val === '1') {
        this.selPayTypeList = []
      }
    },
    changeTimeFalg(val) {
      if (val === '1') {
        this.filters.dateTimes = []
        this.selWeekList = []
        this.param.useRules.useTimeStart = ''
        this.param.useRules.useTimeEnd = ''
        this.param.useRules.useDays = ''
      }
    },
    getCardlevl() {
      cardList({ param: { type: '1' }}).then(res => {
        if (res.errorCode === '000000') {
          this.cardlevl = res.recordList
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getOrderType() {

      this.$nextTick(() => {
        let str = ''
        if (this.param.marketingType === '0') {
          str = 'ORDER_TYPE_MARKETING_REDUCE'
        } else {
          if (this.param.giveType === '0') {
            str = 'ORDER_TYPE_MARKETING_GIVE_FORMONEY'
          } else {
            str = 'ORDER_TYPE_MARKETING_GIVE'
          }
        }
        orderType({ param: { type: str }}).then(res => {
          this.orderTypeList = res.recordList
        })
      })
    },
    changeType(val) {
      this.param.giveItems = ''
      this.getOrderType()
      if (this.param.giveType === '0') {
        this.param.orderTypes = '01'
      }
    },
    // 获取场馆列表
    getVenueList() {
      venueList({
        param: {}
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.filters.venueList = res.recordList
        })
        .catch(() => {})
    },
    // 获取场馆项目
    getVenueProjectList() {
      venueProjectList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.venueProjectListData = res.recordList
        this.venueProjectListDataForTable = res.recordList || []
      })
    },
    reSelectOrderType() {
      this.selCardTypeList = []
      this.checkedVenue = []
      this.checkedItems = []
    },
    // 获取支付方式列表
    getPayTypeList() {
      allConfigList({ param: { type: '2', code: 'PAY_METHOD_MARKETING' }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.payTypeList = res.recordList
      })
    },
    // 重置场馆项目选中状态
    resetVenueProject() {
      const { venueProjectListData, checkedVenue } = this
      const checedList = []
      if (checkedVenue.length === 0) {
        this.venueProjectListDataForTable = venueProjectListData
      } else {
        for (const i in venueProjectListData) {
          for (const j in checkedVenue) {
            if (venueProjectListData[i].id === checkedVenue[j]) {
              checedList.push(venueProjectListData[i])
            }
          }
        }
        this.venueProjectListDataForTable = checedList
      }
    },
    // 选择场馆
    checkVenue(e) {
      const { venueProjectListData } = this
      const checedList = []
      for (const i in venueProjectListData) {
        if (e.includes(venueProjectListData[i].id)) {
          checedList.push(venueProjectListData[i])
        }
      }
      this.venueProjectListDataForTable = checedList
    },
    // 选择项目
    checkProject(e) {
      console.log(e, this.checkedItems)
    },
    compareDate: function(t1, t2) {
      var date = new Date()
      var a = t1.split(':')
      var b = t2.split(':')
      return date.setHours(a[0], a[1]) <= date.setHours(b[0], b[1])
    },
    formateTime(now) {
      var year = now.getFullYear()

      var month =
        (now.getMonth() + 1).toString().length < 2
          ? '0' + (now.getMonth() + 1)
          : now.getMonth() + 1

      var date =
        now.getDate().toString().length < 2
          ? '0' + now.getDate()
          : now.getDate()

      var dateStr =
        year +
        '-' +
        month +
        '-' +
        date
      return dateStr
    },
    onSubmit() {
      const that = this
      this.$refs.form.validate((v) => {
        if (v) {
          that.submitData()
        } else {
          console.log('error submit!!')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.separate{
  width: 100%;
  height: 1px;
  margin: 20px 0px;
  background-color: #DFE2E8;
}
.order_name{
  display: inline-block;
  width: 140px;
  padding-right: 12px;
  color: #606266;
  font-weight: 700;
  text-align: right;
  flex-shrink: 0;
  line-height: 24px;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
  span{
    color: #e47470;
    font-size: 12px;
  }
}
</style>
